#include "parsercombs.h"
#include <iostream>
namespace ParserCombinators
{

using std::string;
using std::vector;

bool skipIW = false;

void ignoreWhitespace(string &in)
{
    skipIW = true;
    while (optionalConsume(in, " "))
    {
        // do nothing
    }
    skipIW = false;
}

void consume(string &in, const string &token)
{
    ignoreWhitespace(in);
    if (in.substr(0, token.length()).compare(token) == 0) 
    {
        in.erase(0, token.length());
    }
    else
    {
        TException up(0, "Expected token \"" + token + "\" not found!");
        throw up;
    }
}

bool optionalConsume(string &in, const string &token)
{
    if (!skipIW)
        ignoreWhitespace(in);
    if (in.substr(0, token.length()).compare(token) == 0) 
    {
        in.erase(0, token.length());
        return true;
    }
    else
    {
        return false;
    }
}

// Applications

bool isDigit(char c)
{
    return (c >= '0' && c <= '9');   
}

int parseInt(string &in)
{
    ignoreWhitespace(in);
    string is = "";
    char c = in.at(0);
    while (isDigit(c)) 
    {
        is.append(1, c);
        in.erase(0, 1);
        c = in.at(0);
    }
    if (is == "0")
        return 0;
    int i = atoi(is.c_str());
    if (i == 0)
    {
        TException up(3, "Expected integer token not found!");
        throw up;
    }
    return i;
}


} // namespace ParserCombinators

